<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
    >
      <el-form-item label="合同编号" prop="contractNo">
        <el-input
          v-model="queryParams.contractNo"
          placeholder="请输入合同编号"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="客户姓名" prop="customerName">
        <el-input
          v-model="queryParams.customerName"
          placeholder="请输入客户姓名"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="客户电话" prop="customerPhone">
        <el-input
          v-model="queryParams.customerPhone"
          placeholder="请输入客户电话"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="支付状态" prop="payStatus">
        <el-select
          v-model="queryParams.payStatus"
          clearable
          placeholder="请选择支付状态"
          style="width: 200px"
        >
          <el-option label="待支付" value="0" />
          <el-option label="已支付" value="1" />
          <el-option label="已退款" value="3" />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:leaseOrder:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          @click="handleExport"
          v-hasPermi="['system:leaseOrder:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="dataList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="合同编号" align="center" prop="contractNo" />
      <el-table-column label="客户姓名" align="center" prop="customerName" />
      <el-table-column label="联系方式" align="center" prop="customerPhone" />
      <el-table-column label="房屋地址" align="center" prop="houseAddress" />
      <el-table-column label="申请人姓名" align="center" prop="askUser" />
      <el-table-column label="区域" align="center" prop="regionName" />
      <el-table-column label="门店" align="center" prop="storeName" />
      <el-table-column label="加盟商" align="center" prop="franchiseeName" />
      <el-table-column label="支付状态" align="center" prop="payStatus">
        <template #default="scope">
          <el-tag type="info" v-if="scope.row.payStatus == 0"> 待支付</el-tag>
          <el-tag type="success" v-if="scope.row.payStatus == 1">
            已支付</el-tag
          >
          <el-tag type="primary" v-if="scope.row.payStatus == 3">
            已退款</el-tag
          >
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        sortable
        width="180"
      >
      </el-table-column>
      <el-table-column
        label="操作"
        width="180"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:leaseOrder:edit']"
            >修改</el-button
          >
          <el-button
            link
            type="primary"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:leaseOrder:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改岗位对话框 -->
    <el-dialog :title="title" v-model="open" width="1000px" append-to-body>
      <div class="contract-container">
        <div class="contract-title">房屋租赁信息</div>
        <el-form
          ref="postRef"
          :model="form"
          label-width="120px"
          label-position="left"
          :rules="rules"
        >
          <!-- 交易类型 -->
          <el-row :gutter="10">
            <el-col :span="12">
              <el-form-item label="客户姓名" prop="customerName">
                <el-input v-model="form.customerName" placeholder="客户姓名" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="客户手机号" prop="customerPhone">
                <el-input
                  v-model="form.customerPhone"
                  maxlength="11"
                  placeholder="客户手机号"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="10">
            <el-col :span="12">
              <el-form-item label="客户身份证号" prop="customerIdCard">
                <el-input
                  v-model="form.customerIdCard"
                  maxlength="18"
                  placeholder="客户身份证号"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="10">
            <el-col :span="12">
              <el-form-item label="业主姓名" prop="ownerName">
                <el-input v-model="form.ownerName" placeholder="业主姓名" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="业主手机号" prop="ownerPhone">
                <el-input
                  v-model="form.ownerPhone"
                  maxlength="11"
                  placeholder="业主手机号"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="10">
            <el-col :span="12">
              <el-form-item label="业主身份证号" prop="ownerIdCard">
                <el-input
                  v-model="form.ownerIdCard"
                  maxlength="18"
                  placeholder="业主身份证号"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 房屋位置信息 -->
          <el-form-item label="房屋位置" prop="propertyObject.provinceName">
            <el-select
              v-model="form.propertyObject.provinceName"
              placeholder="省"
              style="width: 12%; margin-right: 6px"
              @change="selectSheng"
            >
              <el-option
                v-for="item in shengList"
                :key="item.id"
                :label="item.name"
                :value="item.name"
              >
              </el-option>
            </el-select>

            <el-select
              v-model="form.propertyObject.cityName"
              placeholder="市"
              style="width: 12%; margin-right: 6px"
              @change="selectCity"
            >
              <el-option
                v-for="item in cityList"
                :key="item.id"
                :label="item.name"
                :value="item.name"
              >
              </el-option>
            </el-select>
            <el-select
              v-model="form.propertyObject.districtName"
              placeholder="区"
              style="width: 12%; margin-right: 6px"
            >
              <el-option
                v-for="item in quList"
                :key="item.id"
                :label="item.name"
                :value="item.name"
              >
              </el-option>
            </el-select>
            <el-input
              v-model="form.propertyObject.villageName"
              placeholder="小区"
              style="width: 18%; margin-right: 6px"
              @blur="validateHouseAddressField"
            />
            <el-input
              v-model="form.propertyObject.floorName"
              placeholder="楼栋"
              style="width: 12%; margin-right: 6px"
              @blur="validateHouseAddressField"
            />
            <el-input
              v-model="form.propertyObject.elementName"
              placeholder="单元"
              style="width: 12%; margin-right: 6px"
              @blur="validateHouseAddressField"
            />
            <el-input
              v-model="form.propertyObject.roomName"
              placeholder="房间号"
              style="width: 12%"
              @blur="validateHouseAddressField"
            />
          </el-form-item>
          <el-row :gutter="10">
            <el-col :span="12">
              <!-- 应交金额 -->
              <el-form-item label="应交金额" prop="shouldPrice">
                <el-input
                  v-model="form.shouldPrice"
                  placeholder="应交金额"
                  @blur="getItemsPrice"
                >
                  <template #append>元</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <!-- 应交金额 大写-->
              <el-form-item label-width="auto" prop="shouldPriceWords">
                <el-input
                  v-model="form.shouldPriceWords"
                  readonly
                  placeholder="应交金额大写"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <table
            border="1"
            cellspacing="0"
            cellpadding="5"
            style="border-collapse: collapse; width: 100%"
          >
            <thead>
              <tr>
                <th>内容</th>
                <th>店面</th>
                <th>经纪人</th>
                <th>比例</th>
                <th>金额</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(item, index) in form.leaseOrderItemList" :key="index">
                <td>{{ item.content }}</td>
                <td>
                  <el-select
                    v-model="item.storeId"
                    placeholder="请选择"
                    style="width: 150px"
                    @change="selectStoreList(index)"
                    filterable
                  >
                    <el-option
                      v-for="item in allStoreList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    >
                    </el-option>
                  </el-select>
                </td>
                <td>
                  <el-select
                    v-model="item.brokerId"
                    placeholder="请选择"
                    style="width: 150px"
                    filterable
                  >
                    <el-option
                      v-for="item1 in item.brokerArr"
                      :key="item1.id"
                      :label="item1.name"
                      :value="item1.id"
                    >
                    </el-option>
                  </el-select>
                </td>
                <td>
                  <el-input
                    style="width: 150px"
                    placeholder="请输入比例"
                    v-model="item.radio"
                    @blur="setRadioPrice(index)"
                  >
                    <template #append>%</template>
                  </el-input>
                </td>
                <td>{{ item.amount }}元</td>
              </tr>
              <tr>
                <td>实交金额</td>
                <td colspan="4">{{ form.payPrice }}元</td>
              </tr>
            </tbody>
          </table>

          <!-- 区域 -->
          <!-- <el-row :gutter="10">
            <el-col :span="8">
              <el-form-item label="区域" prop="regionId">
                <el-select
                  v-model="form.regionId"
                  filterable
                  clearable
                  placeholder="区域"
                  @change="selectRegin"
                >
                  <el-option
                    v-for="item in companyList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label-width="auto" prop="storeId">
                <el-select
                  v-model="form.storeId"
                  filterable
                  clearable
                  placeholder="门店"
                  @change="selectStore"
                >
                  <el-option
                    v-for="item in storeList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label-width="auto" prop="brokerUserId">
                <el-select
                  v-model="form.brokerUserId"
                  filterable
                  clearable
                  placeholder="经纪人"
                >
                  <el-option
                    v-for="item in agentList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row> -->
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" :loading="subLoad" @click="submitForm"
            >确 定</el-button
          >
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="RentalHouse">
import { getToken } from "@/utils/auth";
import { getCalLetter, getRegionList } from "@/api/contract/contractList";
import {
  showStoreList,
  listBroker,
  addRentalHouse,
  getRentalHouseList,
  getRentalHouse,
  editRentalHouse,
  deleteRentalHouse,
} from "@/api/business/rentalHouse";
import { ref } from "vue";
import { listCompany, listStore, listWorker } from "@/api/business/tcForm";
import { reactive } from "vue";
import router from "@/router";
const { proxy } = getCurrentInstance();
const { sys_normal_disable } = proxy.useDict("sys_normal_disable");
const subLoad = ref(false);
const dataList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    contractNo: undefined,
    contractType: null,
    buyType: null,
  },
});

// 房屋地址验证函数
const validateHouseAddress = (rule, value, callback) => {
  const propertyObject = form.value.propertyObject || {};

  if (!propertyObject.provinceName) {
    return callback(new Error("请选择省份"));
  }
  if (!propertyObject.cityName) {
    return callback(new Error("请选择市"));
  }
  if (!propertyObject.districtName) {
    return callback(new Error("请选择区"));
  }
  if (!propertyObject.villageName) {
    return callback(new Error("请输入小区"));
  }
  if (!propertyObject.floorName) {
    return callback(new Error("请输入楼栋"));
  }
  if (!propertyObject.elementName) {
    return callback(new Error("请输入单元"));
  }
  if (!propertyObject.roomName) {
    return callback(new Error("请输入房间号"));
  }

  callback();
};

// 触发房屋地址验证的函数
const validateHouseAddressField = () => {
  proxy.$refs["postRef"].validateField("propertyObject.provinceName");
};
//验证客户的手机号不能与业主的相同
const validateCustomer = (rule, value, callback) => {
  if (form.value.customerPhone == form.value.ownerPhone) {
    return callback(new Error("客户手机号和业主手机号不能相同"));
  }
  callback();
};

//验证业主的身份证号不能与客户的相同
const validateOwner = (rule, value, callback) => {
  if (form.value.ownerIdCard == form.value.customerIdCard) {
    return callback(new Error("业主身份证号和客户身份证号不能相同"));
  }
  callback();
};
const rules = reactive({
  // 房屋位置
  "propertyObject.provinceName": [
    { required: true, validator: validateHouseAddress, trigger: "change" },
  ],

  totalAmount: [
    { required: true, message: "请输入出售总价", trigger: "blur" },
    {
      pattern: /^\d+(\.\d+)?$/,
      message: "请输入合法的金额",
      trigger: "blur",
    },
  ],
  customerName: [
    { required: true, message: "请输入买方姓名", trigger: "blur" },
  ],
  customerIdCard: [
    { required: true, message: "请输入买方身份证号", trigger: "blur" },
    {
      pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
      message: "身份证格式不正确",
      trigger: "blur",
    },
  ],
  customerPhone: [
    { required: true, message: "请输入买方联系电话", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "手机号格式不正确",
      trigger: "blur",
    },
  ],
  ownerName: [{ required: true, message: "请输入业主姓名", trigger: "blur" }],
  ownerPhone: [
    { required: true, message: "请输入业主手机号", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "手机号格式不正确",
      trigger: "blur",
    },
    { validator: validateCustomer, trigger: "blur" },
  ],
  ownerIdCard: [
    { required: true, message: "请输入业主身份证号", trigger: "blur" },
    {
      pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
      message: "身份证格式不正确",
      trigger: "blur",
    },
    { validator: validateOwner, trigger: "blur" },
  ],

  regionId: [{ required: true, message: "请选择区域", trigger: "change" }],
  storeId: [{ required: true, message: "请选择门店", trigger: "change" }],
  brokerUserId: [
    { required: true, message: "请选择经纪人", trigger: "change" },
  ],
});

//监听比例
function setRadioPrice(index) {
  if (!form.value.shouldPrice) {
    proxy.$modal.alertError("请先输入应交金额");
    return;
  }
  form.value.leaseOrderItemList[index].amount =
    (form.value.leaseOrderItemList[index].radio / 100) * form.value.shouldPrice;

  form.value.payPrice = form.value.leaseOrderItemList.reduce((acc, item) => {
    if (item.content != "成交") {
      return acc + item.amount;
    }
    return acc;
  }, 0);
}
//监听应交金额
function getItemsPrice() {
  //实交金额
  form.value.payPrice = 0;
  form.value.leaseOrderItemList.forEach((item) => {
    item.amount = (item.radio / 100) * form.value.shouldPrice;
    if (item.content != "成交") {
      form.value.payPrice += item.amount;
    }
  });
  //获取大写金额
  getCalLetter({ amount: form.value.shouldPrice }).then((res) => {
    form.value.shouldPriceWords = res.msg;
  });
}
//监听店面选择获取经济人列表
function selectStoreList(index, type = 1) {
  if (type == 1) {
    form.value.leaseOrderItemList[index].brokerId = "";
  }
  listBroker({ storeId: form.value.leaseOrderItemList[index].storeId }).then(
    (res) => {
      form.value.leaseOrderItemList[index].brokerArr = res.data;
    }
  );
}
//成本管理
function handleCost(row) {
  router.push({
    path: "/business/costManager",
    query: { contractNo: row.contractNo },
  });
}

const { queryParams, form } = toRefs(data);

//区域门店经纪人
const companyList = ref([]);
function getAreaList() {
  listCompany().then((res) => {
    companyList.value = res.data;
  });
}
getAreaList();
const storeList = ref([]);
function selectRegin(val) {
  listStore({ regionId: val }).then((res) => {
    storeList.value = res.data;
    form.value.storeId = "";
    form.value.brokerUserId = "";
  });
}
const agentList = ref([]);
function selectStore(val) {
  listWorker({ storeId: val }).then((res) => {
    agentList.value = res.data;
    form.value.brokerUserId = "";
  });
}

//省市区
const shengList = ref([]);
const cityList = ref([]);
const quList = ref([]);
async function getRegin(level, parentId) {
  return new Promise((resolve, reject) => {
    getRegionList({ level, parentId }).then((res) => {
      if (level == 1) {
        shengList.value = res.data;
        resolve(shengList);
      } else if (level == 2) {
        cityList.value = res.data;
        resolve(cityList);
      } else {
        quList.value = res.data;
        resolve(quList);
      }
    });
  });
}
async function selectSheng(val, type = 1) {
  const parent = shengList.value.find((sheng) => sheng.name === val);
  if (type == 1) {
    form.value.propertyObject.cityName = "";
    form.value.propertyObject.districtName = "";
  }

  const cityList = await getRegin(2, parent.id);
  return cityList;
}

async function selectCity(val, type = 1) {
  const parent = cityList.value.find((city) => city.name === val);
  if (type == 1) {
    form.value.propertyObject.districtName = "";
  }
  const quList = await getRegin(3, parent.id);
  return quList;
}
getRegin(1);

/** 查询岗位列表 */
function getList() {
  loading.value = true;
  getRentalHouseList(queryParams.value).then((response) => {
    dataList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

/** 表单重置 */
function reset() {
  form.value = {
    propertyObject: {},
    payPrice: 0,
    leaseOrderItemList: [
      {
        content: "成交",
        storeName: "",
        storeId: "",
        brokerName: "",
        brokerId: "",
        radio: "80",
        amount: "",
        brokerArr: [],
      },
      {
        content: "录入",
        storeName: "",
        storeId: "",
        brokerName: "",
        brokerId: "",
        radio: "8",
        amount: "",
        brokerArr: [],
      },
      {
        content: "实勘",
        storeName: "",
        storeId: "",
        brokerName: "",
        brokerId: "",
        radio: "3",
        amount: "",
        brokerArr: [],
      },
      {
        content: "钥匙",
        storeName: "",
        storeId: "",
        brokerName: "",
        brokerId: "",
        radio: "3",
        amount: "",
        brokerArr: [],
      },
      {
        content: "公司",
        storeName: "",
        storeId: "",
        brokerName: "",
        brokerId: "",
        radio: "6",
        amount: "",
        brokerArr: [],
      },
    ],
  };
  proxy.resetForm("postRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.postId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

//店面列表
const allStoreList = ref([]);
function getStoreList() {
  showStoreList().then((res) => {
    allStoreList.value = res.data;
  });
}
/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加";
  getStoreList();
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  getStoreList();
  const id = row.id || ids.value;
  getRentalHouse(id).then(async (response) => {
    form.value = response.data;
    form.value.leaseOrderItemList.forEach((item, index) => {
      selectStoreList(index, 2);
    });

    await selectSheng(form.value.propertyObject.provinceName, 2);

    await selectCity(form.value.propertyObject.cityName, 2);
    // listStore({ regionId: form.value.regionId }).then((res) => {
    //   storeList.value = res.data;
    // });
    // listWorker({ storeId: form.value.storeId }).then((res) => {
    //   agentList.value = res.data;
    // });
    open.value = true;
    title.value = "修改";
  });
}
function validateItemsRadio() {
  const totalRadio = form.value.leaseOrderItemList.reduce((acc, item) => {
    return acc + Number(item.radio);
  }, 0);
  if (totalRadio != 100) {
    proxy.$modal.alertError("比例总和必须为100%");
    return false;
  }
  return true;
}
/** 提交按钮 */
function submitForm() {
  if (!validateItemsRadio()) {
    return;
  }
  proxy.$refs["postRef"].validate((valid) => {
    if (valid) {
      form.value.leaseOrderItemList = form.value.leaseOrderItemList.map(
        (item) => {
          const { brokerArr, ...reset } = item;
          return reset;
        }
      );
      subLoad.value = true;
      if (form.value.id != undefined) {
        editRentalHouse(form.value)
          .then((response) => {
            proxy.$modal.msgSuccess("修改成功");
            subLoad.value = false;
            open.value = false;
            getList();
          })
          .catch((err) => {
            subLoad.value = false;
          });
      } else {
        addRentalHouse(form.value)
          .then((response) => {
            proxy.$modal.msgSuccess("新增成功");
            subLoad.value = false;
            open.value = false;
            getList();
          })
          .catch((err) => {
            subLoad.value = false;
          });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const id = row.id || ids.value;
  proxy.$modal
    .confirm("是否确认删除？")
    .then(function () {
      return deleteRentalHouse(id);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 下载模板操作 */
function handleExport() {
  proxy.download(
    "system/leaseOrder/export",
    { ...queryParams.value },
    `leaseOrder_${new Date().getTime()}.xlsx`
  );
}

getList();
</script>
<style scoped lang="scss">
.contract-container {
  border: 1px solid #dcdfe6;
  padding: 20px;
  font-family: "Microsoft YaHei", sans-serif;
  background-color: #fff;
  .el-form-item {
    margin-bottom: 18px;
    display: flex;
    align-items: center;
  }
}
.contract-title {
  font-weight: bold;
  text-align: center;
  margin-bottom: 20px;
  font-size: 16px;
}

.checkbox-row {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}
table tr th {
  width: 20%;
}
table tr td {
  text-align: center;
}
</style>
